package com.googlesource.gerrit.plugins.examples.servlet.export;

import com.alibaba.fastjson.JSON;
import com.google.gerrit.extensions.annotations.PluginCanonicalWebUrl;
import com.google.gerrit.extensions.annotations.PluginName;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.googlesource.gerrit.plugins.examples.servlet.HttpClientUtil;
import com.googlesource.gerrit.plugins.examples.servlet.Result;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class BeforeExportServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private static final Logger log = LoggerFactory.getLogger(BeforeExportServlet.class);

  @Inject
  BeforeExportServlet(@PluginName String pluginName, @PluginCanonicalWebUrl String url) {
    log.info(String.format("Cookbook Plugin '%s' at url %s", pluginName, url));
  }

  @Override
  protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
      throws IOException, ServletException {
    // 空占位符
    log.info("request.getParameter('q')={}", request.getParameter("q"));
    Cookie[] cookie = request.getCookies();
    if (cookie == null) {
      response.getWriter().println(JSON.toJSONString(new Result(401, "UNAUTHORIZED")));
    } else {
      // 获取结果
      String result = HttpClientUtil
          .sendGet("changes/?o=LABELS&o=DETAILED_ACCOUNTS&n=1&S=0&q=" + request.getParameter("q"), request).substring(4)
          .trim();
      // 如果为空 直接结束不导出
      if (StringUtils.isEmpty(result)) {
        response.getWriter().println(JSON.toJSONString(new Result(502, "SERVER ERROR")));
      } else if (result.equals("[]")) {
        response.getWriter().println(JSON.toJSONString(new Result(504, "EMPTY RESULT")));
      } else
        response.getWriter().println(JSON.toJSONString(new Result(200, "SUCCESS")));
    }

  }

  @Override
  protected void doPost(final HttpServletRequest req, final HttpServletResponse rsp)
      throws IOException, ServletException {

  }

}